package com.lonely.order.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lonely.common.core.domain.TimeLine;
import com.lonely.common.enums.CommonStatus;
import com.lonely.common.utils.SecurityUtils;
import com.lonely.order.domain.entity.SysOrderSecondProcessLog;
import com.lonely.order.mapper.SysOrderSecondProcessLogMapper;
import com.lonely.order.service.IOrderSecondProcessLogService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author : 黄志标
 * @date: 2025/8/6 16:08
 * @description: 订单二次工艺日志服务实现类
 */
@Service
public class OrderSecondProcessLogServiceImpl extends ServiceImpl<SysOrderSecondProcessLogMapper, SysOrderSecondProcessLog> implements IOrderSecondProcessLogService {

    /**
     * 添加日志
     *
     * @param orderSecondProcessId
     * @param title
     * @param body
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addLog(Long orderSecondProcessId, String title, String body) {
        SysOrderSecondProcessLog sysOrderSecondProcessLog = new SysOrderSecondProcessLog();
        sysOrderSecondProcessLog.setOrderSecondProcessId(orderSecondProcessId);
        sysOrderSecondProcessLog.setLogTitle(title);
        sysOrderSecondProcessLog.setLogBody(body);
        sysOrderSecondProcessLog.setCreateBy(SecurityUtils.getUserId());
        sysOrderSecondProcessLog.setUpdateBy(SecurityUtils.getUserId());
        super.save(sysOrderSecondProcessLog);
    }

    /**
     * 获取指定二次工艺id对应的的日志时间线
     *
     * @param secondProcessId
     * @return
     */
    @Override
    public List<TimeLine> getLogTimeLine(Long secondProcessId) {
        return super.list(new LambdaQueryWrapper<SysOrderSecondProcessLog>()
                        .eq(SysOrderSecondProcessLog::getOrderSecondProcessId, secondProcessId)
                        .eq(SysOrderSecondProcessLog::getStatus, CommonStatus.ENABLE.code)
                        .orderByDesc(SysOrderSecondProcessLog::getCreateTime))
                .stream().map(currentSecondProcessLog -> {
                    TimeLine timeLine = new TimeLine();
                    timeLine.setType("info");
                    timeLine.setContent(currentSecondProcessLog.getLogBody());
                    timeLine.setTitle(currentSecondProcessLog.getLogTitle());
                    timeLine.setTime(DateUtil.formatDateTime(currentSecondProcessLog.getCreateTime()));
                    return timeLine;
                }).collect(Collectors.toList());
    }
}
